#include "AutoDetectParameters.h"
#include <QThread>
#include <QMessageBox>
#include <QWebPage>
#include <QNetworkAccessManager>
#include <QNetworkConfiguration>
#include <QCryptographicHash>
#include <qsysteminfo.h>


AutoDetectParameters* AutoDetectParameters::instance = NULL;

AutoDetectParameters* AutoDetectParameters::Instance()
{
        if(instance==NULL)
            instance=new AutoDetectParameters();
        return instance;
}

class FriendlyWebPage : public QWebPage
{
public:
    friend class AutoDetectParameters;
};

AutoDetectParameters::AutoDetectParameters()
{
        qWarning("Create AutoDetectParameters");
        m_dLat = m_dLon = 0;
        getGpsCoordinates();

        QSystemDeviceInfo sysInfo;

        QString imei = sysInfo.imei();
        QCryptographicHash md5(QCryptographicHash::Md5);
        md5.addData(imei.toAscii());
        m_strDeviceID = md5.result().toHex().constData();
        connect(this,SIGNAL(onCreate()),this, SLOT(updateUA()));

        emit onCreate();
        qWarning("Created AutoDetectParameters");
}

void AutoDetectParameters::updateUA()
{
    qWarning("Update User Agent");
    FriendlyWebPage page;
    m_ua = page.userAgentForUrl(QUrl(""));
    qWarning("User Agent Updated");
}

void AutoDetectParameters::updateMyPosition(QGeoPositionInfo info){
    if (info.isValid())
        {
            qWarning("Update position");
            // We've got the position. No need to continue the listening.
            positionSource->stopUpdates();

            // Save the position information into a member variable
            myPositionInfo = info;

            // Get the current location as latitude and longitude
            QGeoCoordinate geoCoordinate = info.coordinate();
            m_dLat = geoCoordinate.latitude();
            m_dLon = geoCoordinate.longitude();
        }
}


void AutoDetectParameters::getGpsCoordinates(){
    if (!positionSource)
    {
        positionSource =
            QGeoPositionInfoSource::createDefaultSource(this);
        // Whenever the location data source signals that the current
        // position is updated, the positionUpdated function is called
        connect(positionSource, SIGNAL(positionUpdated(QGeoPositionInfo)),
                      this, SLOT(updateMyPosition(QGeoPositionInfo)));

        // Start listening for position updates
        positionSource->startUpdates();
    }

}
